/*******************************************************************************************
Copyright (C) 2017 Mestrelab Research S.L. All rights reserved.

This file is part of the Mnova scripting toolkit.

Authorized users of MNova Software may use this file freely, but this file is provided AS IS
with NO WARRANTY OF ANY KIND, INCLUDING THE WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE.
*******************************************************************************************/

/*globals NMRSpectrum, MessageBox, nmr, mainWindow, MnUi*/

/*jslint plusplus: true, continue: true, indent: 4*/

function unfold2d() {
	"use strict";

	var origSpec, recSpec, startY, endY, i, np, ni, matrix, swppm1, swppm2, corrStartX, corrStartY;

	origSpec = nmr.activeSpectrum();
	if (!origSpec.isValid()) {
		MessageBox.critical("NMR spectrum is not found");
		return;
	}
	if (origSpec.dimCount !== 2) {
		MessageBox.critical("This script is applicable for 2D spectra only");
		return;
	}

	np = origSpec.count(2);
	ni = origSpec.count(1);

	swppm1 = (origSpec.getFullScaleLimits().toY - origSpec.getFullScaleLimits().fromY) / (ni - 1) * ni; //see comment http://192.168.2.8/issues/11982#note-3
	swppm2 = (origSpec.getFullScaleLimits().toX - origSpec.getFullScaleLimits().fromX) / (np - 1) * np;

	corrStartY = origSpec.getFullScaleLimits().toY - swppm1;
	corrStartX = origSpec.getFullScaleLimits().toX - swppm2;

	startY = corrStartY - swppm1;
	endY = origSpec.getFullScaleLimits().toY + swppm1;

	recSpec = new NMRSpectrum(
		{
			1: {nucleus: origSpec.nucleus(1, false), frequency: origSpec.frequency(1), from_ppm: startY, to_ppm: endY, size: origSpec.count(1) * 3},
			2: {nucleus: origSpec.nucleus(2, false), frequency: origSpec.frequency(2), from_ppm: corrStartX, to_ppm: origSpec.getFullScaleLimits().toX, size: origSpec.count(2)},
			filename: origSpec.originalFileName,
			origin: 'Unfolded',
			title: origSpec.title
		}
	);

	recSpec.threshold = origSpec.threshold;
	recSpec.experimentType = origSpec.experimentType;

	matrix = origSpec.real({from: 0, to: ni - 1}, {from: 0, to: np - 1});
	nmr.beginModification(recSpec);
	for (i = 0; i < 3; i++) {
		recSpec.setReal({from: i * ni, to: i * ni + ni - 1}, {from: 0, to: np - 1}, matrix);
	}
	nmr.endModification(recSpec);

	recSpec.update();
	mainWindow.activeDocument.update();
}

if (this.MnUi && MnUi.scripts_nmr) {
	MnUi.scripts_nmr.scripts_nmr_unfold2d = unfold2d;
}
